/*
 * AdminLogIn.java
 *
 * Created on 10 April 2008, 0:43
 */
package usu.buku.telepon.admin;

import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import usu.buku.telepon.exception.DataNotCompleteException;
import usu.buku.telepon.sql.MySQL;
import usu.buku.telepon.widget.worker.WorkerAction;
import usu.buku.telepon.widget.worker.WorkerTeman;
import usu.widget.Form;
import usu.widget.util.WidgetUtilities;

/**
 *
 * @author  usu
 */
public class AdminForm extends Form {

   private static final long serialVersionUID = -1;
   private GraphicsDevice gd;
   private Connection connection;

   /** Creates new form BeanForm */
   public AdminForm() {

      gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();

      setIconImage(new ImageIcon(getClass().getResource("/usu/buku/telepon/resource/small.png")).getImage());

      initComponents();
      initActions();
   }

   private void initActions() {
      // Teman
      panelTeman.addActionListenerSegarkan(new AksiButton_Teman_Segarkan());
      panelTeman.addActionListenerTambah(new AksiButton_Teman_Tambah());
      panelTeman.addActionListenerUbah(new AksiButton_Teman_Ubah());
      panelTeman.addActionListenerHapus(new AksiButton_Teman_Hapus());
      panelTeman.addActionListenerSaring(new AksiButton_Teman_saring());

      // Tambah Teman
      tambahTeman.addActionListenerBatal(new AksiButton_TambahTeman_Batal());
      tambahTeman.addActionListenerTambah(new AksiButton_TambahTeman_Tambah());

      // Ubah Teman
      ubahTeman.addActionListenerBatal(new AksiButton_UbahTeman_Batal());
      ubahTeman.addActionListenerUbah(new AksiButton_UbahTeman_Ubah());
   }

   /**
    * 
    * @param connection
    */
   public void setConnection(Connection connection) {
      this.connection = connection;
      try {
         new WorkerTeman(connection, panelTeman.getTableModel(), new WorkerAction() {

            @Override
            public void runFirst() {
               panelTeman.reset();
               panelTeman.setEnabled(false);
               labelStatus.setText("Loading Database");
               progressBar.setIndeterminate(true);
            }

            @Override
            public void runLast() {
               panelTeman.setEnabled(true);
               labelStatus.setText("e'PhoneBook");
               progressBar.setIndeterminate(false);
            }
         }).execute();
      } catch (SQLException ex) {
         WidgetUtilities.showErrorMessage(AdminForm.this, ex.getMessage());
      }
   }

   /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        about = new usu.buku.telepon.widget.About();
        glassPane = new usu.widget.GlassPane();
        ubahTeman = new usu.buku.telepon.admin.UbahTeman();
        tambahTeman = new usu.buku.telepon.admin.TambahTeman();
        usu.buku.telepon.widget.Panel panelGradient = new usu.buku.telepon.widget.Panel();
        usu.buku.telepon.widget.Label label2 = new usu.buku.telepon.widget.Label();
        panelTeman = new usu.buku.telepon.admin.PanelTeman();
        usu.buku.telepon.widget.Toolbar toolBar = new usu.buku.telepon.widget.Toolbar();
        buttonFullScreen = new usu.buku.telepon.widget.Button();
        usu.buku.telepon.widget.Button buttonTentang = new usu.buku.telepon.widget.Button();
        usu.buku.telepon.widget.Toolbar statusBar = new usu.buku.telepon.widget.Toolbar();
        labelStatus = new usu.buku.telepon.widget.Label();
        progressBar = new usu.buku.telepon.widget.ProgressBar();

        about.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutActionPerformed(evt);
            }
        });

        setGlassPane(glassPane);
        getGlassPane().setVisible(true);

        setTitle("e'PhoneBook");
        setAnimationHide(usu.widget.constan.Animation.HIDE_TO_LEFT);
        setAnimationShow(usu.widget.constan.Animation.SHOW_FROM_RIGHT);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        label2.setText("e'PhoneBook");
        label2.setFont(new java.awt.Font("Tahoma", 1, 24));

        javax.swing.GroupLayout panelGradientLayout = new javax.swing.GroupLayout(panelGradient);
        panelGradient.setLayout(panelGradientLayout);
        panelGradientLayout.setHorizontalGroup(
            panelGradientLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelGradientLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelGradientLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panelTeman, javax.swing.GroupLayout.DEFAULT_SIZE, 764, Short.MAX_VALUE)
                    .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        panelGradientLayout.setVerticalGroup(
            panelGradientLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelGradientLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelTeman, javax.swing.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE)
                .addContainerGap())
        );

        getContentPane().add(panelGradient, java.awt.BorderLayout.CENTER);

        toolBar.setRollover(true);

        buttonFullScreen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/usu/buku/telepon/resource/home.png"))); // NOI18N
        buttonFullScreen.setMnemonic('L');
        buttonFullScreen.setText("layar penuh");
        buttonFullScreen.setFocusable(false);
        buttonFullScreen.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        buttonFullScreen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonFullScreenActionPerformed(evt);
            }
        });
        toolBar.add(buttonFullScreen);

        buttonTentang.setIcon(new javax.swing.ImageIcon(getClass().getResource("/usu/buku/telepon/resource/tentang.png"))); // NOI18N
        buttonTentang.setMnemonic('T');
        buttonTentang.setText("tentang");
        buttonTentang.setFocusable(false);
        buttonTentang.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        toolBar.add(javax.swing.Box.createHorizontalGlue());
        buttonTentang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonTentangActionPerformed(evt);
            }
        });
        toolBar.add(buttonTentang);

        getContentPane().add(toolBar, java.awt.BorderLayout.PAGE_START);

        statusBar.setRollover(true);

        labelStatus.setText("e'PhoneBook");
        statusBar.add(labelStatus);

        progressBar.setMaximumSize(new java.awt.Dimension(150, 14));
        statusBar.add(javax.swing.Box.createHorizontalGlue());
        statusBar.add(progressBar);

        getContentPane().add(statusBar, java.awt.BorderLayout.PAGE_END);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-800)/2, (screenSize.height-600)/2, 800, 600);
    }// </editor-fold>//GEN-END:initComponents

private void aboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutActionPerformed
   glassPane.hideComponent();
}//GEN-LAST:event_aboutActionPerformed

private void buttonFullScreenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonFullScreenActionPerformed
   if (gd.isFullScreenSupported()) {
      if (gd.getFullScreenWindow() == null) {
         gd.setFullScreenWindow(this);
         buttonFullScreen.setText("keluar layar penuh");
      } else {
         gd.setFullScreenWindow(null);
         buttonFullScreen.setText("layar penuh");
      }
   } else {
      WidgetUtilities.showErrorMessage(this, "Sistem Operasi Anda Tak Mendukung Mode Full Screen");
   }
}//GEN-LAST:event_buttonFullScreenActionPerformed

private void buttonTentangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonTentangActionPerformed
   glassPane.showComponent(about);
}//GEN-LAST:event_buttonTentangActionPerformed

private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
   exit();
}//GEN-LAST:event_formWindowClosing

    // Variables declaration - do not modify//GEN-BEGIN:variables
    usu.buku.telepon.widget.About about;
    usu.buku.telepon.widget.Button buttonFullScreen;
    usu.widget.GlassPane glassPane;
    usu.buku.telepon.widget.Label labelStatus;
    usu.buku.telepon.admin.PanelTeman panelTeman;
    usu.buku.telepon.widget.ProgressBar progressBar;
    usu.buku.telepon.admin.TambahTeman tambahTeman;
    usu.buku.telepon.admin.UbahTeman ubahTeman;
    // End of variables declaration//GEN-END:variables

   class AksiButton_Teman_Segarkan implements ActionListener {

      @Override
      public void actionPerformed(ActionEvent e) {
         try {
            new WorkerTeman(connection, panelTeman.getTableModel(), new WorkerAction() {

               @Override
               public void runFirst() {
                  panelTeman.reset();
                  panelTeman.setEnabled(false);
                  labelStatus.setText("Loading Database");
                  progressBar.setIndeterminate(true);
               }

               @Override
               public void runLast() {
                  panelTeman.setEnabled(true);
                  labelStatus.setText("e'PhoneBook");
                  progressBar.setIndeterminate(false);
               }
            }).execute();
         } catch (SQLException ex) {
            WidgetUtilities.showErrorMessage(AdminForm.this, ex.getMessage());
         }
      }
   }

   class AksiButton_Teman_saring implements ActionListener {

      @Override
      public void actionPerformed(ActionEvent e) {
         try {
            new WorkerTeman(connection, panelTeman.getTableModel(), new WorkerAction() {

               @Override
               public void runFirst() {
                  panelTeman.setEnabled(false);
                  labelStatus.setText("Loading Database");
                  progressBar.setIndeterminate(true);
               }

               @Override
               public void runLast() {
                  panelTeman.setEnabled(true);
                  labelStatus.setText("e'PhoneBook");
                  progressBar.setIndeterminate(false);
               }
            }, panelTeman.getNama(), panelTeman.getTelepon()).execute();
         } catch (SQLException ex) {
            WidgetUtilities.showErrorMessage(AdminForm.this, ex.getMessage());
         }
      }
   }

   class AksiButton_Teman_Tambah implements ActionListener {

      @Override
      public void actionPerformed(ActionEvent e) {
         tambahTeman.reset();
         glassPane.showComponent(tambahTeman);
      }
   }

   class AksiButton_TambahTeman_Batal implements ActionListener {

      @Override
      public void actionPerformed(ActionEvent e) {
         glassPane.hideComponent();
      }
   }

   class AksiButton_UbahTeman_Batal implements ActionListener {

      @Override
      public void actionPerformed(ActionEvent e) {
         glassPane.hideComponent();
      }
   }

   class AksiButton_TambahTeman_Tambah implements ActionListener {

      @Override
      public void actionPerformed(ActionEvent e) {
         Savepoint save;
         try {
            save = connection.setSavepoint();
            try {
               MySQL.insertTeman(connection, tambahTeman.getTeman());
               panelTeman.getTableModel().add(tambahTeman.getTeman());
               glassPane.hideComponent();
            } catch (DataNotCompleteException ex) {
               connection.rollback(save);
               WidgetUtilities.showErrorMessage(AdminForm.this, ex.getMessage());
            } catch (SQLException ex) {
               connection.rollback(save);
               WidgetUtilities.showErrorMessage(AdminForm.this, ex.getMessage());
            } finally {
               connection.releaseSavepoint(save);
            }
         } catch (SQLException ex) {
            Logger.getLogger(AdminForm.class.getName()).log(Level.SEVERE, null, ex);
         }
      }
   }

   class AksiButton_Teman_Ubah implements ActionListener {

      @Override
      public void actionPerformed(ActionEvent e) {
         if (panelTeman.getTable().getSelectedRowCount() == 0) {
            WidgetUtilities.showErrorMessage(AdminForm.this, "teman yang akan diubah belum dipilih");
            return;
         }
         int index = panelTeman.getTable().convertRowIndexToModel(panelTeman.getTable().getSelectedRow());
         ubahTeman.setTeman(panelTeman.getTableModel().get(index));
         glassPane.showComponent(ubahTeman);
      }
   }

   class AksiButton_UbahTeman_Ubah implements ActionListener {

      @Override
      public void actionPerformed(ActionEvent e) {
         try {
            Savepoint save = connection.setSavepoint();
            try {
               MySQL.updateTeman(connection, ubahTeman.getTeman().getId(), ubahTeman.getTeman());
               int index = panelTeman.getTable().convertRowIndexToModel(panelTeman.getTable().getSelectedRow());
               panelTeman.getTableModel().set(index, ubahTeman.getTeman());
               glassPane.hideComponent();
            } catch (DataNotCompleteException ex) {
               connection.rollback(save);
               WidgetUtilities.showErrorMessage(AdminForm.this, ex.getMessage());
            } catch (SQLException ex) {
               connection.rollback(save);
               WidgetUtilities.showErrorMessage(AdminForm.this, ex.getMessage());
            } finally {
               connection.releaseSavepoint(save);
            }
         } catch (SQLException ex) {
            Logger.getLogger(AdminForm.class.getName()).log(Level.SEVERE, null, ex);
         }
      }
   }

   class AksiButton_Teman_Hapus implements ActionListener {

      @Override
      public void actionPerformed(ActionEvent e) {
         try {
            if (panelTeman.getTable().getSelectedRowCount() == 0) {
               WidgetUtilities.showErrorMessage(AdminForm.this, "teman yang akan dihapus belum dipilih");
               return;
            }
            if (WidgetUtilities.showConfirmMessage(AdminForm.this, "anda yakin?") != JOptionPane.OK_OPTION) {
               return;
            }
            connection.setAutoCommit(false);
            while (panelTeman.getTable().getSelectedRowCount() > 0) {
               try {
                  int index = panelTeman.getTable().convertRowIndexToModel(panelTeman.getTable().getSelectionModel().getMaxSelectionIndex());
                  MySQL.deleteTeman(connection, panelTeman.getTableModel().get(index).getId());
                  panelTeman.getTableModel().remove(index);
               } catch (SQLException ex) {
                  WidgetUtilities.showErrorMessage(AdminForm.this, ex.getMessage());
               }
            }
            connection.commit();
            connection.setAutoCommit(true);
         } catch (SQLException ex) {
            Logger.getLogger(AdminForm.class.getName()).log(Level.SEVERE, null, ex);
         }
      }
   }
}